package com.handu.luna.core.domain;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

import com.handu.luna.core.domain.Context.Environment;

/**
 * 数据源配置类
 * 如果是开发环境，返回内置数据库数据源
 * 如果正式或者测试环境，则返回tomcat配置的数据源
 * @author zhangwen
 */
@Configuration
public class DataSourceConfiguration {
	
	@Value("${spring.datasource.testUrl:jdbc:mysql://localhost/test}")
	private String testUrl = "jdbc:mysql://localhost/test";

	/*@Value("${spring.datasource.testUrl:jdbc:mysql://localhost/test}")
    private String testUrl = "jdbc:mysql://localhost/test";*/
	
	@Value("${spring.datasource.testDriverClassName:com.mysql.jdbc.Driver}")
	private String testDriverClassName = "com.mysql.jdbc.Driver";
	
	@Value("${spring.datasource.testUser:root}")
	private String testUser = "root";

	@Value("${spring.datasource.testPassword:123456}")
	private String testPassword = "123456";
	
	@Bean
	@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
	public DataSource dataSource() {
		Context context = new Context();
		Context.initEnvironment(context);
		if(context.environment == Environment.DEVELOP || context.environment == Environment.UNIT_TEST){
			EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2);
			return builder.build();
		}else if(context.environment == Environment.TEST){
			return DataSourceBuilder.create()
					.type(org.apache.tomcat.jdbc.pool.DataSource.class)
					.url(testUrl)
					.driverClassName(testDriverClassName)
					.username(testUser)
					.password(testPassword)
					.build();
		}else{
			return DataSourceBuilder.create()
					.type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
		}

	}
}

